package com.cc.secondKill.controller;


import com.cc.secondKill.commnons.JsonUtils;
import com.cc.secondKill.commnons.ShardedJedisPoolUtils;
import com.cc.secondKill.pojo.Goods;
import com.cc.secondKill.pojo.MiaoshaMessage;
import com.cc.secondKill.pojo.Order;
import com.cc.secondKill.pojo.User;
import com.cc.secondKill.rabbit.MQSender;
import com.cc.secondKill.service.impl.GoodsService;
import com.cc.secondKill.service.impl.OrderService;
import com.cc.secondKill.service.impl.UserService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resources;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

@Controller
public class UserController implements InitializingBean {

    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MQSender mqSender;



    @Override
    @Deprecated
    public void afterPropertiesSet() throws Exception {
        List<Goods> goodsList = this.goodsService.getGoodsList();
        for (Goods goods : goodsList){
            ShardedJedisPoolUtils.set("goodsStock"+goods.getId(), String.valueOf(goods.getStock()));
            ShardedJedisPoolUtils.set("goods"+goods.getId(), JsonUtils.obj2String(goods));
        }
    }

    @RequestMapping(value = "/login.do")
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/doLogin.do", method = RequestMethod.POST)
    public String doLogin(Model model, User user, HttpServletRequest request){
        if (user.getName() == null || user.getPhone() == null){
            return "error";
        }
        request.getSession().setAttribute("user",user);
        List<Goods> goodsList = this.goodsService.getGoodsList();
        if (goodsList == null){
            model.addAttribute("good_msg","阶段性秒杀还未开始，暂时没有商品信息");
        }else{
            model.addAttribute("goodsList",goodsList);
        }
        if (this.userService.insertUserInfo(user)){
            model.addAttribute("msg","已自动注册为用户");
            return "list";
        }
        model.addAttribute("msg","用户已参与过类似秒杀活动，无需注册，自动登陆");
        return "list";
    }

    @RequestMapping("doSecKill.do")
    @ResponseBody
    @Deprecated
    public Object doSecKill(HttpServletRequest request){
        String userPhone = request.getParameter("userPhone");
        userPhone = userPhone + String.valueOf(System.currentTimeMillis())+String.valueOf(System.currentTimeMillis()).substring(10,13);
        String goodsId = request.getParameter("goodsId");
        Map<String,String> result = new HashMap<String, String>();
        Goods goods = JsonUtils.String2Obj(ShardedJedisPoolUtils.get("goods"+goodsId),Goods.class);
        if (new Date().getTime() < goods.getStartTime().getTime()){
            result.put("msg","秒杀还未开始");
            return result;
        }
        if (new Date().getTime() > goods.getEndTime().getTime()){
            result.put("msg","秒杀已经结束");
            return result;
        }
        Order order = this.orderService.getOrderByGoodsIdAndPhone(userPhone,Integer.parseInt(goodsId));
        if (order != null){
            result.put("msg","该用户已经参加过秒杀，不能重复秒杀");
            return result;
        }else{
            if (goods.getStock() <= 0){
                result.put("msg","当前产品库存为0，无法秒杀");
                return result;
            }
            //开始秒杀，已经开始，尚未结束，没有参加过且库存>0
            long stock = ShardedJedisPoolUtils.decr("goodsStock"+goodsId);
            MiaoshaMessage miaoshaMessage = new MiaoshaMessage();
            miaoshaMessage.setGoodsId(Integer.parseInt(goodsId));
            miaoshaMessage.setUserPhone(userPhone);
            mqSender.sendMiaoshaMessage(miaoshaMessage);
            result.put("msg","排队中...");
            result.put("code","1");
            return result;
        }
    }

    @RequestMapping("/msResult.do")
    @ResponseBody
    public Object getMsResult(HttpServletRequest request){
        String userPhone = request.getParameter("userPhone");
        String goodsId = request.getParameter("goodsId");
        Map<String,String> result = new HashMap<String, String>();
        if (userPhone == null || goodsId == null){
            return null;
        }
        Order order = this.orderService.getOrderByGoodsIdAndPhone(userPhone,Integer.parseInt(goodsId));
        if (order != null){
            result.put("msg","秒杀成功!");
            return result;
        }else{
            result.put("msg","秒杀失败,请重新尝试");
            return result;
        }
    }
}
